var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

app.get('/', (req, res)=>{
  res.setHeader('Content-Type', 'text/plain;charset=utf-8');
  res.end('第一条路由');
});

app.get('/about', (req, res)=>{
  res.setHeader('Content-Type', 'text/plain;charset=utf-8');
  res.end('关于XXXX');
});

app.get('/login', (req, res)=>{
  // res.setHeader('Content-Type', 'text/plain;charset=utf-8');
  res.end('进入登录模块，请输入用户名和密码');
});

app.post('/login', (req, res)=>{
  // res.setHeader('Access-Control-Allow-Origin','*');
  // res.setHeader('Content-Type', 'text/plain;charset=utf-8');
  res.end('POST的响应')
})

app.all('/list', (req, res)=>{
  // res.setHeader('Access-Control-Allow-Origin','*');
  // res.setHeader('Content-Type', 'text/plain;charset=utf-8');
  res.send('来自接口 list 的响应');
})

app.use('/user/:id/file/:fid', (req, res)=>{
  res.setHeader('Access-Control-Allow-Origin','*');
  res.setHeader('Content-Type', 'text/plain;charset=utf-8');
  console.log(req.params);
  res.end('来自接口 user 的响应，数据是： \n' + JSON.stringify(req.params));
});

var f0 = function(req,res,next){
  console.log('f0');
  next();
}

var f1 = function(req,res,next){
  console.log('f1');
  // res.send('f1');
  next();
}

var f2 = function(req,res,next){
  console.log('f2');
  res.send('f2');
  next();
}

app.use('/test', [f0,f1], function(req, res){
  console.log('临时加一个');
  res.send('临时加一个');
});


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
